package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.ProjectCollectOriginal;
import com.isunland.managesystem.entity.SimpleTreeListParams;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.ZTreeNode;
import com.isunland.managesystem.entity.ZTreeNodeListOriginal;
import com.isunland.managesystem.entity.rBuyappMain;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.Date;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/6/12 18:36
 */
public class BuyApplyFragment extends BaseFragment implements View.OnClickListener {
  public static final String EXTRA_CONTENT =
      BuyApplyFragment.class.getSimpleName() + ".EXTRA_CONTENT";
  @BindView(R.id.sl_materialKindName) SingleLineView slMaterialKindName;
  @BindView(R.id.sl_buyappSum) SingleLineView slBuyappSum;
  @BindView(R.id.sl_projectName) SingleLineView slProjectName;
  @BindView(R.id.et_buyappCom) EditText etBuyappCom;
  @BindView(R.id.et_remark) EditText etRemark;
  @BindView(R.id.sl_buyappDate) SingleLineView slBuyappDate;
  @BindView(R.id.sl_mainproject) SingleLineView slMainproject;
  @BindView(R.id.sl_buyappName) SingleLineView slBuyappName;
  @BindView(R.id.sl_buyappDeptName) SingleLineView slBuyappDeptName;
  @BindView(R.id.sl_buyappStatus) SingleLineView slBuyappStatus;
  @BindView(R.id.sl_buyappNo) SingleLineView slBuyappNo;
  @BindView(R.id.sl_buyPurposeName) SingleLineView slBuyPurposeName;
  private rBuyappMain mContent;
  private String mId;
  private String materialKindCode;
  private String projectId;
  private String buyappDeptCode;
  private String buyPurposeCode;
  private int menuType;
  private int REQUEST_MATERIALKIND = 0;
  private int REQUEST_PROJECT = 1;
  private final int ADD = 2;
  private final int NEW = 3;
  private final int SUB = 4;
  private final int PUBLISH = 5;
  private final int REQUEST_DEPT = 6;
  private int REQUEST_SUBMIT = 7;
  private int REQUEST_DELETE = 8;
  private int REQUEST_BUYPURPOSE = 9;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.buyApply);
    mContent = (rBuyappMain) getArguments().getSerializable(EXTRA_CONTENT);
    if (mContent == null) {
      //添加: 保存,保存并提交
      menuType = ADD;
      mId = UUID.randomUUID().toString();
      materialKindCode = "";
      buyappDeptCode = mCurrentUser.getDeptCode();
      projectId = "";
      buyPurposeCode = "";
    }
    if (mContent != null) {
      mId = mContent.getId();
      materialKindCode = mContent.getMaterialKindCode();
      buyappDeptCode = mContent.getBuyappDeptCode();
      projectId = mContent.getProjectId();
      buyPurposeCode = mContent.getBuyPurposeCode();

      String dataStatus = mContent.getBuyappStatusName();
      //详情
      if (DataStatus.NEW.equalsIgnoreCase(dataStatus) || DataStatus.ABORT.equalsIgnoreCase(
          dataStatus)) {
        //草稿:保存,提交,删除
        //终止: 保存,提交,删除
        menuType = NEW;
      } else if (DataStatus.WAIT_CHECK.equalsIgnoreCase(dataStatus)) {
        //提交: 终止流程
        menuType = SUB;
      } else {
        menuType = PUBLISH;
      }
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    switch (menuType) {
      //草稿状态：保存、保存并提交
      case ADD:
        inflater.inflate(R.menu.menu_save_submit, menu);
        break;
      //草稿状态：保存、提交、删除
      case NEW:
        inflater.inflate(R.menu.menu_save_submit_delete, menu);
        break;
      //提交状态：返回修改
      case SUB:
        inflater.inflate(R.menu.menu_stop, menu);
        break;
      case PUBLISH:
        break;
      default:
        break;
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_save:
        //保存
        if (isCorrectInput()) {
          String SAVE = "save";
          volleyPostSave(SAVE);
        }
        return true;
      case R.id.menu_item_submit:
        //保存并提交
        boolean isCorrectSubmit = isCorrectInput();
        if (isCorrectSubmit) {
          showDialog(BaseConfirmDialogFragment.newInstance(R.string.start_up_hint), REQUEST_SUBMIT);
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        showDialog(BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm), REQUEST_DELETE);
        return true;
      case R.id.menu_item_stop:
        // 返回修改
        volleyPostStop();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override protected int initLayoutId() {
    return R.layout.fragment_buy_appply_detail;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    if (mContent != null) {
      //详情
      slMaterialKindName.setTextContent(mContent.getMaterialKindName());
      slBuyappSum.setTextContent(mContent.getBuyappSum());
      slBuyPurposeName.setTextContent(mContent.getBuyPurposeName());
      slProjectName.setTextContent(mContent.getProjectName());
      etBuyappCom.setText(mContent.getBuyappCom());
      etRemark.setText(mContent.getRemark());
      slBuyappDate.setTextContent(mContent.getBuyappDate());
      slBuyappName.setTextContent(mContent.getBuyappName());
      slBuyappDeptName.setTextContent(mContent.getBuyappDeptName());
      MyUtils.switchDataStutus(getActivity(), slBuyappStatus.getViewContent(),
          mContent.getBuyappStatusName());
      slBuyappNo.setTextContent(mContent.getBuyappNo());
    } else {
      //添加
      slBuyappDate.setTextContent(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));
      slBuyappName.setTextContent(mCurrentUser.getRealName());
      slBuyappDeptName.setTextContent(mCurrentUser.getDeptName());
      MyUtils.switchDataStutus(getActivity(), slBuyappStatus.getViewContent(), DataStatus.NEW);
    }

    if (SUB == menuType || PUBLISH == menuType) {
      disableView();
    }
    slMaterialKindName.setOnClickContentListener(this);
    slBuyPurposeName.setOnClickContentListener(this);
    slProjectName.setOnClickContentListener(this);
    slBuyappDeptName.setOnClickContentListener(this);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View rootView = super.onCreateView(inflater, container, savedInstanceState);
    ButterKnife.bind(this, rootView);
    return rootView;
  }

  @Override public void onClick(View view) {
    if (!(view.getTag() instanceof Integer)) return;
    int id = (int) view.getTag();
    switch (id) {
      case R.id.sl_materialKindName:
        //物料类别
        volleyPostMateria();
        break;
      case R.id.sl_buyPurposeName:
        //采购用途
        showDialog( BuyPurposeDialogFragment.newInstance(BuyPurposeDialogFragment.DETAIL), REQUEST_BUYPURPOSE);
        break;
      case R.id.sl_projectName:
        //项目名称
        getProject();
        break;
      case R.id.sl_buyappDeptName:
        //部门
        volleyPostDeptKind();
        break;
    }
  }

  /*禁用输入和选择*/
  private void disableView() {
    slMaterialKindName.getViewContent().setEnabled(false);
    slBuyappSum.getViewContent().setEnabled(false);
    slBuyPurposeName.getViewContent().setEnabled(false);
    slProjectName.getViewContent().setEnabled(false);
    etBuyappCom.setEnabled(false);
    etRemark.setEnabled(false);
    slBuyappDate.getViewContent().setEnabled(false);
    slMainproject.getViewContent().setEnabled(false);
    slBuyappDeptName.getViewContent().setEnabled(false);
  }

  private void volleyPostMateria() {
    SimpleTreeListParams params = new SimpleTreeListParams();
    //noinspection unchecked
    ZTreeNode item = new ZTreeNode();
    item.setName("");
    item.setId("");
    params.setItem(item);
    params.setChildField("id");
    params.setParentField("pid");
    params.setTitleField("name");
    params.setTitle("物料类别");
    params.setClassOriginal(ZTreeNodeListOriginal.class);
    params.setUrl(ApiConst.URL_BUY_MATERIE_LOM);
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode())
            .put("dataStatus", "publish"));
    BaseVolleyActivity.newInstance(this, ZTreeListActivity.class, params, REQUEST_MATERIALKIND);
  }

  /* 部门树  */
  private void volleyPostDeptKind() {
    SimpleTreeListParams params = new SimpleTreeListParams();
    //noinspection unchecked
    ZTreeNode item = new ZTreeNode();
    item.setName("");
    item.setId("");
    //noinspection unchecked
    params.setItem(item);
    params.setChildField("id");
    params.setParentField("pid");
    params.setTitleField("name");
    params.setContentField("extParam2");
    params.setTitle("选择部门");
    params.setClassOriginal(ZTreeNodeListOriginal.class);
    params.setUrl(ApiConst.URL_QUERY_LIST_DEPT_TREE);
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode())
            .put("type", "mobile"));
    BaseVolleyActivity.newInstance(this, ZTreeListActivity.class, params, REQUEST_DEPT);
  }

  private void getProject() {
    Intent project = new Intent(getActivity(), ProjectChooseListActivity.class);
    startActivityForResult(project, REQUEST_PROJECT);
  }

  /*判断必填项*/
  private boolean isCorrectInput() {
    if (TextUtils.isEmpty(slMaterialKindName.getTextContent()) || TextUtils.isEmpty(
        slBuyPurposeName.getTextContent())) {
      ToastUtil.show(R.string.notComplete);
      return false;
    } else {
      return true;
    }
  }

  /*保存*/
  private void volleyPostSave(String type) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_BUY_APPLY_SAVE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    params.put("materialKindCode", materialKindCode);
    params.put("materialKindName", slMaterialKindName.getTextContent());
    params.put("buyappSum", slBuyappSum.getTextContent());
    params.put("buyPurposeCode", buyPurposeCode);
    params.put("buyPurposeName", slBuyPurposeName.getTextContent());
    params.put("projectName", slProjectName.getTextContent());
    params.put("projectId", projectId);
    params.put("buyappCom", etBuyappCom.getText().toString());
    params.put("buyappDeptName", slBuyappDeptName.getTextContent());
    params.put("buyappDeptCode", buyappDeptCode);
    params.put("remark", etRemark.getText().toString());
    params.put("saveOrRun ", type);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  /*删除*/
  private void volleyPostDel() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_BUY_APPLY_DEL);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  /*终止*/
  private void volleyPostStop() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_BUY_APPLY_STATUS);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    params.put("buyappStatusName", DataStatus.ABORT);
    params.put("runId", mContent.getRunId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  private VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage message = new Gson().fromJson(json, SuccessMessage.class);
        if (message.getResult() == null) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        if (message.getResult() != null && SuccessMessage.SUCCESS.equalsIgnoreCase(
            message.getResult())) {

          ToastUtil.show(R.string.success_operation);
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
        if (message.getResult() != null && SuccessMessage.FAILURE.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(message.getMessage());
        }
      }
    };
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_OK) return;

    if (requestCode == REQUEST_MATERIALKIND) {
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      ZTreeNode item = ((ZTreeNode) params.getItem());
      //materialKindCode = item.getCustomAttrs();
      materialKindCode = item.getId();
      slMaterialKindName.setTextContent(item.getName());
    }
    if (requestCode == REQUEST_PROJECT) {
      ProjectCollectOriginal.ProjectCollectContent objectContent =
          (ProjectCollectOriginal.ProjectCollectContent) data.getSerializableExtra(
              ProjectChooseListFragment.EXTRA_CONTENT);
      projectId = objectContent.getId();
      slProjectName.setTextContent(objectContent.getProjectName());
    }
    if (requestCode == REQUEST_DEPT) {
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      ZTreeNode item = ((ZTreeNode) params.getItem());
      buyappDeptCode = item.getExtParam();
      slBuyappDeptName.setTextContent(item.getName());
    }
    if (requestCode == REQUEST_BUYPURPOSE) {
      //采购用途
      CustomerDialog content =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      buyPurposeCode = content.getId();
      slBuyPurposeName.setTextContent(content.getName());
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDel();
    }
    if (requestCode == REQUEST_SUBMIT) {
      String RUN = "run";
      volleyPostSave(RUN);
    }
  }

  public static BuyApplyFragment newInstance(rBuyappMain content) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    BuyApplyFragment fragment = new BuyApplyFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
